--[[
-- Author:      feilong
-- DateTime:    2018-04-23 17:19:33
-- Description:

--]]
local socket = require "skynet.socket"

---------------------------------------------------------
-- class
---------------------------------------------------------
local Service = class("Service")

function Service:ctor(name)
	self.ip = "0.0.0.0"
	self.port = 8001
	self.socket_id = 0
	self:register()
end

function Service:register()
	g.dispatch:register('start', handler(self, self.onStart))
	g.dispatch:register('close', handler(self, self.onClose))

end

function Service:onStart()
	--起动http服务
	local agent = {}
	local agent_num = 1
	for i= 1, agent_num do
		agent[i] = g.newService("agent.service", i)
	end
	local balance = 1
	local id = socket.listen(self.ip, self.port)
	self.socket_id = id
	g.log:info(string.format("http listen: %s %s", self.ip, self.port))
	local function start_callback(id, addr)
		--收到请求
		g.log:info("accept message:", {id=id, addr=addr})
		g.send(agent[balance], "accept", id)
		balance = balance + 1 --把请求分散到各个agent处理
		if balance > agent_num then
			balance = 1
		end
	end
	socket.start(id, start_callback)

	return true
end

function Service:onClose()
	g.exit()
	return true
end


return Service
